package com.tanhua.mongodbManager.service.impl;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.tanhua.mongodbManager.domain.PageResult;
import com.tanhua.mongodbManager.domain.mongod.DynamicValidateForm;
import com.tanhua.mongodbManager.domain.mongod.Question;
import com.tanhua.mongodbManager.domain.mongod.QuestionOption;
import com.tanhua.mongodbManager.domain.mongod.Questionnarie;
import com.tanhua.mongodbManager.domain.vo.OptionsVo;
import com.tanhua.mongodbManager.domain.vo.QuestionnarieVo;
import com.tanhua.mongodbManager.service.QuestionService;
import com.tanhua.mongodbManager.utils.ListPageUtil;
import org.apache.commons.collections.ListUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @ClassName -> QuestionServiceImpl
 * @Description
 * @Author OHC
 * @Date 2021/8/19 星期四
 */
@Service
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询所有问题
     */
    @Override
    public PageResult findAllQuestion(Integer page, Integer pagesize) {
        //查询问卷表的数据
        List<Questionnarie> questionnarieList = mongoTemplate.findAll(Questionnarie.class);
        List<QuestionnarieVo> questionnarieVos = new ArrayList<>();

        //查询到的问卷答案的总数
        Long count = 0L;
        Query query;
        for (Questionnarie questionnarie : questionnarieList) {
            query = new Query(Criteria.where("questionnaireId").is(questionnarie.getId()));
            //查询全部
            List<Question> questionList = mongoTemplate.find(query, Question.class);
            count += mongoTemplate.count(query, Question.class);

            for (Question question : questionList) {
                QuestionnarieVo questionnarieVo = new QuestionnarieVo();
                //设置问卷表id
                questionnarieVo.setQuestionLevel(questionnarie.getLevel());
                questionnarieVo.setQuestionId(question.getId().toString());
                questionnarieVo.setQuestionText(question.getText());
                questionnarieVos.add(questionnarieVo);
            }
        }

        ListPageUtil listPageUtil = new ListPageUtil(questionnarieVos, page, pagesize);
        List pagedList = listPageUtil.getPagedList();
        PageResult pageResult = new PageResult(page, pagesize, count.intValue(), pagedList);
        return pageResult;
    }

    /**
     * 搜索
     */
    @Override
    public PageResult searchQuestion(Integer page, Integer pagesize, String queryQuestion) {
        List<QuestionnarieVo> questionnarieVos = new ArrayList<>();
        //查询到的问卷答案的总数
        Long count = 0L;
        Query query;
        if (!"".equals(queryQuestion)) {
            Pattern pattern = Pattern.compile("^.*" + queryQuestion + ".*$", Pattern.CASE_INSENSITIVE);
            query = new Query().addCriteria(Criteria.where("text").regex(pattern));
            List<Question> questionList = mongoTemplate.find(query, Question.class);
            count += mongoTemplate.count(query, Question.class);

            for (Question question : questionList) {
                QuestionnarieVo questionnarieVo = new QuestionnarieVo();
                //设置问卷表等级
                query = new Query(Criteria.where("_id").is(question.getQuestionnaireId()));
                Questionnarie questionnarie = mongoTemplate.findOne(query, Questionnarie.class);
                questionnarieVo.setQuestionLevel(questionnarie.getLevel());
                //设置问题id
                questionnarieVo.setQuestionId(question.getId().toString());
                //设置问题
                questionnarieVo.setQuestionText(question.getText());
                questionnarieVos.add(questionnarieVo);
            }
        }

        PageResult pageResult;
        if (questionnarieVos.size() != 0) {
            ListPageUtil listPageUtil = new ListPageUtil(questionnarieVos, 1, count.intValue());
            List<QuestionnarieVo> pagedList = listPageUtil.getPagedList();
            pageResult = new PageResult(1, count.intValue(), count.intValue(), pagedList);
        } else {
            pageResult = new PageResult(page, pagesize, count.intValue(), questionnarieVos);
        }
        return pageResult;
    }

    @Override
    public Long addAndModify(Map<String, Object> param) {

        //1.根据等级表查询问卷表
        String level = (String) param.get("level");//等级
        Query query = new Query(Criteria.where("level").is(level));
        Questionnarie questionnarie = mongoTemplate.findOne(query, Questionnarie.class);


        //2.往问卷表中添加数据
        ObjectId questionnarieId = questionnarie.getId();
        String questionText = (String) param.get("question"); //获取问题文本
        Question question = new Question();
        question.setText(questionText);//设置问题文本
        question.setQuestionnaireId(questionnarieId);//设置问题等级的id
        Question insertQuestion = mongoTemplate.insert(question);

        //3.往选项表中添加数据
        //选项的集合
        ArrayList<Map<String, Object>> optionsList = (ArrayList<Map<String, Object>>) param.get("options");
        Long count = 0L;
        for (Map<String, Object> options : optionsList) {
            QuestionOption questionOption = new QuestionOption();
            questionOption.setQuestionId(insertQuestion.getId());
            //选项
            String option = (String) options.get("option");
            questionOption.setContext(option);
            //分值
            String points = (String) options.get("points");
            //判断分值是否大于10,如果大于10就将分值设为10
            if (Integer.parseInt(points) > 10) {
                questionOption.setWeight("10");
            } else {
                questionOption.setWeight(points);
            }
            //添加到选项表中
            mongoTemplate.insert(questionOption);
            count += 1;//添加成功的数量
        }

        /*//问题的id
        String questionId = (String) param.get("questionId");*/
        return count;
    }

    /**
     * 删除问题
     */
    @Override
    public Long removeQuestion(String questionId) {
        //获取问题表的id
        ObjectId questionIdDB = new ObjectId(questionId);
        //根据id删除问题表的数据
        Query query = new Query(Criteria.where("_id").is(questionIdDB));
        DeleteResult removeQuestion = mongoTemplate.remove(query, Question.class);
        //根据id删除选项表的选项
        query = new Query(Criteria.where("questionId").is(questionIdDB));
        DeleteResult removeQuestionOption = mongoTemplate.remove(query, QuestionOption.class);
        //返回删除的条数
        Long row = removeQuestionOption.getDeletedCount() + removeQuestion.getDeletedCount();
        return row;
    }


    /**
     * 更新选项
     */
    @Override
    public Long fixTheProblem(DynamicValidateForm dynamicValidateForm) {
        //获取questionId
        ObjectId questionId = new ObjectId(dynamicValidateForm.getQuestionId());

        //查询问题表
        Query query = new Query(Criteria.where("_id").is(questionId));
        Question question = mongoTemplate.findOne(query, Question.class);

        //查询问卷表,获取等级
        query = new Query(Criteria.where("_id").is(question.getQuestionnaireId()));
        Questionnarie questionnarie = mongoTemplate.findOne(query, Questionnarie.class);

        //查询选项表
        query = new Query(Criteria.where("questionId").is(questionId));
        List<QuestionOption> questionOptions = mongoTemplate.find(query, QuestionOption.class);
        //封装数据
        DynamicValidateForm dynamicValidateFormDB = new DynamicValidateForm();
        //问题表的问题
        dynamicValidateFormDB.setQuestion(question.getText());
        //问题表的id
        dynamicValidateFormDB.setQuestionId(question.getId().toString());
        //问题表单的等级
        dynamicValidateFormDB.setLevel(questionnarie.getLevel());
        //选项表的数据
        ArrayList<OptionsVo> optionsVos = new ArrayList<>();
        for (QuestionOption questionOption : questionOptions) {
            OptionsVo optionsVo = new OptionsVo();
            optionsVo.setId(questionOption.getId().toString());//设置id
            optionsVo.setOption(questionOption.getContext());//设置选项
            optionsVo.setPoints(questionOption.getWeight());//设置分值
            optionsVos.add(optionsVo);
        }
        dynamicValidateFormDB.setOptions(optionsVos);

        //判断数据对象和前端传过来的数据是否相同
        if (dynamicValidateFormDB.equals(dynamicValidateForm)) {
            return 0L;
        }


        //根据level查询数据id
        query = new Query(Criteria.where("level").is(dynamicValidateForm.getLevel()));
        Questionnarie templateOne = mongoTemplate.findOne(query, Questionnarie.class);

        //更新问卷等级
        if (!dynamicValidateForm.getLevel().equals(questionnarie.getLevel())) {
            query = new Query(Criteria.where("_id").is(new ObjectId(dynamicValidateForm.getQuestionId())));
            //根据level查询数据
            Update update = new Update();
            update.set("questionnaireId", templateOne.getId());
            mongoTemplate.updateFirst(query, update, Question.class);
        }

        //更新选项表
        ArrayList<OptionsVo> optionsDB = dynamicValidateFormDB.getOptions();
        ArrayList<OptionsVo> frontEndParam = dynamicValidateForm.getOptions();

        //找出相同的更新
        List<OptionsVo> retainAll = ListUtils.retainAll(frontEndParam, optionsDB);
        Long count = 0L;
        for (OptionsVo option : retainAll) {
            query = new Query(Criteria.where("_id").is(new ObjectId(option.getId())));
            Update update = new Update();
            update.set("context", option.getOption());
            //判断设置的分数是否大于10，如果大于10就修改为10
            if (Integer.parseInt(option.getPoints()) > 10) {
                update.set("weight", "10");
            } else {
                update.set("weight", option.getPoints());
            }
            mongoTemplate.updateFirst(query, update, QuestionOption.class);
            count += 1;
        }

        //新增选项
        List<OptionsVo> addOptions = ListUtils.removeAll(frontEndParam, optionsDB);
        if (addOptions.size() != 0) {
            for (OptionsVo option : addOptions) {
                QuestionOption questionOption = new QuestionOption();
                questionOption.setQuestionId(questionId);
                questionOption.setContext(option.getOption());
                //判断设置的分数是否大于10，如果大于10就修改为10
                if (Integer.parseInt(option.getPoints()) > 10) {
                    questionOption.setWeight("10");
                } else {
                    questionOption.setWeight(option.getPoints());
                }
                mongoTemplate.insert(questionOption);
            }
        }

        //删除选项
        List<OptionsVo> removeOptions = ListUtils.removeAll(optionsDB, frontEndParam);
        if (removeOptions.size() != 0) {
            for (OptionsVo option : removeOptions) {
                query = new Query(Criteria.where("_id").is(new ObjectId(option.getId())));
                mongoTemplate.remove(query, QuestionOption.class);
                count += 1;
            }
        }


        //更新问题表
        ObjectId objectId = new ObjectId(dynamicValidateForm.getQuestionId());
        query = new Query(Criteria.where("_id").is(objectId));
        Update update = new Update();
        update.set("text", dynamicValidateForm.getQuestion());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Question.class);

        //返回更新的总数
        Long totalCount = updateResult.getModifiedCount() + count;
        return totalCount;
    }

    /**
     * 编辑回显数据
     */
    @Override
    public DynamicValidateForm editQuestion(String questionId) {
        Query query;
        ObjectId objectId = new ObjectId(questionId);
        //查询问题表
        query = new Query(Criteria.where("_id").is(questionId));
        Question question = mongoTemplate.findOne(query, Question.class);

        //根据具问题表questionnaireId查询等级
        query = new Query(Criteria.where("_id").is(question.getQuestionnaireId()));
        Questionnarie questionnarie = mongoTemplate.findOne(query, Questionnarie.class);

        //查询选项表
        query = new Query(Criteria.where("questionId").is(objectId));
        List<QuestionOption> questionOptions = mongoTemplate.find(query, QuestionOption.class);
        ArrayList<OptionsVo> optionsVos = new ArrayList<>();
        for (QuestionOption questionOption : questionOptions) {
            OptionsVo optionsVo = new OptionsVo();
            optionsVo.setId(questionOption.getId().toString());
            optionsVo.setOption(questionOption.getContext());
            optionsVo.setPoints(questionOption.getWeight());
            optionsVos.add(optionsVo);
        }

        DynamicValidateForm dynamicValidateForm = new DynamicValidateForm();
        dynamicValidateForm.setOptions(optionsVos);
        dynamicValidateForm.setQuestion(question.getText());
        dynamicValidateForm.setLevel(questionnarie.getLevel());
        dynamicValidateForm.setQuestionId(question.getId().toString());

        return dynamicValidateForm;
    }

}
